package com.smart.sso.server.session.redis;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
import com.smart.sso.server.common.AuthContent;
import com.smart.sso.server.session.CodeManager;

/**
 * 分布式授权码管理
 * 
 * @author Joe
 */
@Component
@ConditionalOnProperty(name = "sso.session.manager", havingValue = "redis")
@Slf4j
public class RedisCodeManager implements CodeManager {

	@Autowired
	private StringRedisTemplate redisTemplate;

	private static final ObjectMapper objectMapper = new ObjectMapper();

	@Override
	public void create(String code, AuthContent authContent) {
		try {
			redisTemplate.opsForValue().set(code, objectMapper.writeValueAsString(authContent), getExpiresIn(), TimeUnit.SECONDS);
		} catch (JsonProcessingException e) {
			log.error("JsonProcessingException:{}",e);
		}
	}

	@Override
	public AuthContent validate(String code) {
		String cc = redisTemplate.opsForValue().get(code);
		if (!StringUtils.isEmpty(cc)) {
			redisTemplate.delete(code);
		}
		try {
			return objectMapper.readValue(cc, AuthContent.class);
		} catch (IOException e) {
			log.error("IOException:{}",e);
		}
		return null;
	}
}
